package com.chap5_2;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * <code>TryLock</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-28 10:09
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class TryLock {
    private static Lock No13 = new ReentrantLock();
    private static Lock No14 = new ReentrantLock();

    private static  void method1() throws InterruptedException {
        String name = Thread.currentThread().getName();
        Random r = new Random();
        while (true){
            if (No13.tryLock()){
                System.out.println(name +" get No13");
                try {
                    if (No14.tryLock()){
                        try{
                            System.out.println(name + " get 14");
                            System.out.println("method1.......");
                            break;
                        }finally {
                            No14.unlock();
                        }
                    }
                }finally {
                    No13.unlock();
                }
            }
//            Thread.sleep(r.nextInt(3));
        }
    }

    private static  void method2() throws InterruptedException {
        String name = Thread.currentThread().getName();
        Random r = new Random();
        while (true){
            if (No14.tryLock()){
                System.out.println(name +" get No14");
                try {
                    if (No13.tryLock()){
                        try{
                            System.out.println(name + " get 13");
                            System.out.println("method2.......");
                            break;
                        }finally {
                            No13.unlock();
                        }
                    }
                }finally {
                    No14.unlock();
                }
            }
//            Thread.sleep(r.nextInt(3));
        }
    }

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    method1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"张三").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    method2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"李四").start();
    }
}
